﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Honestysoft.Financing.DataAccess;
using Honestysoft.Financing.Model;
using System.Data.Common;
using Honestysoft.BaseObject;

namespace Honestysoft.Financing.BusinessLogic
{
    public class Contract
    {
        string _connectionStringName;
        /// <summary>
        /// 构造函数，使用指定的连接字符串
        /// </summary>
        /// <param name="connectionStringName">连接字符串名称</param>
        public Contract(string connectionStringName)
        {
            _connectionStringName = connectionStringName;
        }

        public DataTable GetChildNode(string parentId)
        {
            if (string.IsNullOrEmpty(parentId))
            {
                return new BD_Contract_DAL(_connectionStringName).GetRootNode();
            }
            else
            {
                return new BD_Contract_DAL(_connectionStringName).GetChildNode(parentId);
            }
        }
        /// <summary>
        /// 得到合同信息列表
        /// </summary>
        /// <param name="projectCategory"></param>
        /// <param name="projectId"></param>
        /// <param name="projectName"></param>
        /// <param name="category"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetContracts(string projectCategory, string projectId,string projectName, string category, string code, string name, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            return new BD_Contract_DAL(_connectionStringName).GetContracts(projectCategory, projectId, projectName, category, code, name, pageSize, currentPageIndex, out pageCount, out recordCount);
        }
        /// <summary>
        /// 确认合同初始化
        /// </summary>
        /// <param name="arrId"></param>
        /// <param name="userId"></param>
        /// <param name="confirmTime"></param>
        /// <param name="opinion"></param>
        /// <returns></returns>
        public bool ConfirmInit(string[] arrId, string userId, DateTime confirmTime, string opinion)
        {
            return new BD_Contract_DAL(_connectionStringName).ConfirmInit(arrId, userId, confirmTime, opinion);
        }

        /// <summary>
        /// 得到合同信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BD_Contract GetContract(string id)
        {
            BD_Contract contract = new BD_Contract_DAL(_connectionStringName).GetContract(id);
            if (contract != null)
            {
                QueryParameters query = new QueryParameters();
                query.Add("ContractID",id, QueryParameters.OperatorType.Equal);
                OrderParameters order = new OrderParameters();
                order.Add("changeDate", OrderParameters.OrderDirection.Desc);
                order.Add("CreateTime", OrderParameters.OrderDirection.Desc);
                contract.ContractChanges = new BD_ContractChange_DAL(_connectionStringName).SelectEntitys(query, order);
            }
            return contract;
        }

        /// <summary>
        /// 得到合同
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="contractCategory"></param>
        /// <param name="isInit"></param>
        /// <returns></returns>
        public DataTable GetContracts(string projectId, string contractCategory, bool? isInit)
        {
            return new BD_Contract_DAL(_connectionStringName).GetContracts(projectId, contractCategory, isInit);
        }
        /// <summary>
        /// 得到各种合同类别的个数
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="isInit"></param>
        /// <returns></returns>
        public DataTable GetContractCategoryCount(string projectId, bool? isInit)
        {
            return new BD_Contract_DAL(_connectionStringName).GetContractCategoryCount(projectId, isInit);
        }
        /// <summary>
        /// 得到合同变更
        /// </summary>
        /// <param name="projectCategory"></param>
        /// <param name="projectId"></param>
        /// <param name="projectName"></param>
        /// <param name="contractCategory"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetContractChange(string projectCategory, string projectId, string projectName, string contractCategory, string code, string name,string id, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            return new BD_ContractChange_DAL(_connectionStringName).GetContractChange(projectCategory, projectId, projectName, contractCategory, code, name,id, pageSize, currentPageIndex, out pageCount, out recordCount);
        }
        /// <summary>
        /// 得到合同的项目信息
        /// </summary>
        /// <param name="arrId"></param>
        /// <returns></returns>
        public DataTable GetContractProject(string[] arrId)
        {
            return new BD_Contract_DAL(_connectionStringName).GetContractProject(arrId);
        }

        /// <summary>
        /// 是否已存在该合同编号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool IsExistsContractCode(string code)
        {
            return new BD_Contract_DAL(_connectionStringName).IsExistsCode(code);
        }
        /// <summary>
        /// 是否已存在该合同名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool IsExistsContractName(string name)
        {
            return new BD_Contract_DAL(_connectionStringName).IsExistsName(name);
        }

        /// <summary>
        /// 得到项目下合同的下一个编号
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public string GetNextContractCode(string projectId)
        {
            return new BD_Contract_DAL(_connectionStringName).GetNextContractCode(projectId);
        }

        /// <summary>
        /// 保存合同
        /// 注意：需要设置合同的数据状态DataState
        /// </summary>
        /// <param name="contract"></param>
        /// <returns></returns>
        public bool SaveContract(BD_Contract contract,string dOwnerCompanyIDStr,DbTransaction transaction)
        {
            BD_Contract_ProjectDOwner_DAL dal = new BD_Contract_ProjectDOwner_DAL(_connectionStringName);
            QueryParameters query = new QueryParameters();
            query.Add("ContractID", contract.ID, QueryParameters.OperatorType.Equal);
            dal.Delete(query, transaction);
            List<BD_Contract_ProjectDOwner> lsDOwner = new List<BD_Contract_ProjectDOwner>();
            if (!string.IsNullOrEmpty(dOwnerCompanyIDStr))
            {
                string[] arrCompID = dOwnerCompanyIDStr.Split(',');                
                BD_Contract_ProjectDOwner item = null;
                foreach (string s in arrCompID)
                {
                    item = new BD_Contract_ProjectDOwner();
                    item.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                    item.CompanyID = s;
                    item.ContractID = contract.ID;
                    lsDOwner.Add(item);
                }
            }
            if (contract.dataState == EnumItem.DataState.New)
            {
                new BD_Contract_DAL(_connectionStringName).InsertEntity(contract, transaction);
                if (contract.ContractChanges != null && contract.ContractChanges.Count > 0)
                {
                    new BD_ContractChange_DAL(_connectionStringName).InsertEntitys(contract.ContractChanges, transaction);
                }
                if (lsDOwner.Count > 0)
                {
                    dal.InsertEntitys(lsDOwner, transaction);
                }
            }
            else
            {
                BD_Contract_DAL dal1 = new BD_Contract_DAL(_connectionStringName);
                dal1.UpdateEntity(contract, transaction);
                if (lsDOwner.Count > 0)
                {
                    dal.InsertEntitys(lsDOwner, transaction);
                }
                //new Bu_DocReceive_Temp_DAL(_connectionStringName).UpdateContractInfo(contract, transaction);
                //Bu_AuditTable_DAL atDAL = new Bu_AuditTable_DAL(_connectionStringName);
                //atDAL.UpdateContractInfo(contract, transaction);
                //atDAL.DeleteATDOwnerInfo(contract.ID, transaction);
                //if (lsDOwner.Count > 0)
                //{
                //    atDAL.InsertATDOwnerInfo(contract.ID, transaction);
                //}
                dal1.RefreshATContractInfo(contract.ID, transaction);
                if (contract.ContractChanges != null && contract.ContractChanges.Count > 0)
                {
                    contract.ContractChanges = contract.ContractChanges.FindAll((BD_ContractChange find) => find.dataState == EnumItem.DataState.New);
                    if (contract.ContractChanges != null && contract.ContractChanges.Count > 0)
                    {
                        new BD_ContractChange_DAL(_connectionStringName).InsertEntitys(contract.ContractChanges, transaction);
                    }
                }
            }
            
            
            return true;
        }
        /// <summary>
        /// 合同入库
        /// </summary>
        /// <param name="contract"></param>
        /// <param name="docRecID"></param>
        /// <returns></returns>
        public bool ContractToDatabase(BD_Contract contract, string docRecID,string toCompanyID,string dOwnerCompanyIDStr, DbTransaction transaction)
        {
            bool bRet = false;
            try
            {
                contract.IsInit = true;
                contract.ConfirmOpinion = "";
                contract.ConfirmTime = contract.CreateTime;
                contract.ConfirmUser = contract.Creator;
                Bu_DocReceive_Temp_DAL dal1 = new Bu_DocReceive_Temp_DAL(_connectionStringName);
                Bu_DocReceive_Temp docRec = dal1.SelectEntityByKey(docRecID, transaction);
                new BD_Contract_DAL(_connectionStringName).InsertEntity(contract, transaction);
                
                if (contract.ContractChanges != null && contract.ContractChanges.Count > 0)
                {
                    new BD_ContractChange_DAL(_connectionStringName).InsertEntitys(contract.ContractChanges, transaction);
                }
                if (!string.IsNullOrEmpty(dOwnerCompanyIDStr))
                {
                    string[] arrCompID = dOwnerCompanyIDStr.Split(',');
                    List<BD_Contract_ProjectDOwner> lsDOwner = new List<BD_Contract_ProjectDOwner>();
                    BD_Contract_ProjectDOwner item = null;
                    foreach (string s in arrCompID)
                    {
                        item = new BD_Contract_ProjectDOwner();
                        item.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                        item.CompanyID = s;
                        item.ContractID = contract.ID;
                        lsDOwner.Add(item);
                    }
                    new BD_Contract_ProjectDOwner_DAL(_connectionStringName).InsertEntitys(lsDOwner, transaction);
                }
                docRec.ContractID = contract.ID;
                docRec.ContractName = contract.Name;
                docRec.ContractCode = contract.Code;
                docRec.IsToDBCon = true;
                Bu_DocReceive docRec2 = new Bu_DocReceive(docRec);
                //修改为取建设单位（首次收文回执里面填写什么，则是什么）
                //docRec2.FromCompany = contract.Contractor;
                docRec2.FromCompany = new Reports(_connectionStringName).GetCompanyIdByName(docRec.FromCompanyName, transaction);
                if (docRec2.FromCompany == "")
                {
                    docRec2.FromCompany = new BD_Project_DAL(_connectionStringName).SelectEntityByKey(contract.ProjectID, transaction).Owner;
                }
                docRec2.ToCompany = toCompanyID;
                dal1.UpdateEntity(docRec, transaction);
                new Bu_DocReceive_DAL(_connectionStringName).InsertEntity(docRec2, transaction);
                bRet = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return bRet;
        }


        /// <summary>
        /// 得到相似的合同（使用价格）
        /// </summary>
        /// <param name="price"></param>
        /// <returns></returns>
        public DataTable GetLikeContractByPrice(decimal price)
        {
            return new BD_Contract_DAL(_connectionStringName).GetLikeContractByPrice( price);
        }

        /// <summary>
        /// 得到相似的合同（使用名称）
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public DataTable GetLikeContractByName(string name)
        {
            return new BD_Contract_DAL(_connectionStringName).GetLikeContractByName(name);
        }
    }
}
